package domain.message ;

import java.util.List;
import java.util.Vector;

import persistence.Persistent;
import presentation.UIThread;

/**
 * class Thread. represents linear structure of posts on the same topic. holds all the posts ids.
 */
public class Thread extends Persistent implements UIThread
{
	private static final long serialVersionUID = -1789060734186747036L ;

	/** the vector that holds all the posts id's in this Thread **/
	private Vector<Long> posts ;
	private String topic ;

	/**
	 * @param id id of this thread.
	 * @param topic topic of this thread.
	 */
	public Thread(final long id, final String topic)
	{
		super(id) ;
		this.topic = topic ;
		this.posts = new Vector<Long>() ;
	}

	// for serialization
	@SuppressWarnings("unused")
	private Thread()
	{
		super(Persistent.INVALID_ID) ;
		this.posts = null ;
		this.topic = null ;
	}

	/**
	 * add a post to the thread
	 * @param postId id of the post to add to this thread.
	 */
	public void addPost(final long postId)
	{
		this.lockWrite() ;
		try
		{
			this.posts.add(postId) ;
		}
		finally
		{
			this.unlockWrite() ;
		}
	}

	/**
	 * delete a post from this thread
	 * @param postId id of the post to remove from this thread.
	 */
	public void deletePost(final long postId)
	{
		this.lockWrite() ;
		try
		{
			this.posts.remove(postId) ;
		}
		finally
		{
			this.unlockWrite() ;
		}
	}

	/**
	 * @return posts in this thread.
	 */
	public Vector<Long> getPosts()
	{
		this.lockRead() ;
		try
		{
			return this.posts ;
		}
		finally
		{
			this.unlockRead() ;
		}
	}

	/**
	 * @return topic of this thread.
	 */
	public String getTopic()
	{
		this.lockRead() ;
		try
		{
			return this.topic ;
		}
		finally
		{
			this.unlockRead() ;
		}
	}

	/**
	 * set the thread's topic
	 * @param topic the thread's new topic
	 */
	public void setTopic(final String topic)
	{
		this.lockWrite() ;
		try
		{
			this.topic = topic ;
		}
		finally
		{
			this.unlockWrite() ;
		}
	}

	/**
	 * function for debugging-return string with threads info
	 * @see persistence.Persistent#toString()
	 */
	@Override
	public String toString()
	{
		return super.toString() + " " + this.getTopic() ;
	}

	/**
	 * @param posts list of posts to set.
	 */
	protected void setPosts(final List<Long> posts)
	{
		this.lockWrite() ;
		try
		{
			this.posts = new Vector<Long>(posts) ;
		}
		finally
		{
			this.unlockWrite() ;
		}
	}
}
